var express = require('express');
var router = express.Router();
var teacherData = require('../data/teacherData.js');

router.get('/list', function (req, res, next) {
    if (!req.query.pageIndex) {
        res.send('缺少pageIndex')
    }

    if (!req.query.pageSize) {
        res.send('缺少pageSize')
    }

    let data = teacherData.filter(item => {
        return item.teacherId.includes(req.query.teacherId) && item.teacherName.includes(req.query.teacherName)
    })

    let start = (Number(req.query.pageIndex) - 1) * req.query.pageSize
    let end = Number(req.query.pageIndex) * req.query.pageSize

    res.send({
        pageIndex: req.query.pageIndex,
        pageSize: req.query.pageSize,
        total: data.length,
        data: data.slice(start, end)
    })
})

router.post('/add', function (req, res, next) {

    let data = {
        teacherId: req.body.teacherId,
        teacherName: req.body.teacherName,
        sex: req.body.sex,
        age: req.body.age,
        identityCard: req.body.identityCard,
        teachingCourses: req.body.teachingCourses
    }

    teacherData.push(data)

    res.send({
        msg: '新增成功',
        code: 200,
        data: true
    })
})

router.put('/update', function (req, res, next) {
    if (!req.body.teacherId) {
        res.send('缺少id字段')

        return
    }

    let index = teacherData.findIndex(item => {
        return String(item.teacherId) === String(req.body.teacherId)
    })

    console.log('index',index)
    if (index < 0) {
        res.send({
            msg: '编辑失败，未通过teacherId找到对应数据',
            code: 500,
            data: false
        })

        return
    }

    teacherData[index] = Object.assign({}, req.body)

    res.send({
        msg: '编辑成功',
        code: 200,
        data: true
    })
})

router.delete('/delete', function (req, res, next) {
    console.log(req.query)
    if (!req.query.teacherId) {
        res.send('缺少teacherId字段')
    }

    let index = teacherData.findIndex(item => {
        return Number(item.teacherId) === Number(req.query.teacherId)
    })

    if (index < 0) {
        res.send({
            msg: '删除失败，未能通过teacherId找到对应数据',
            code: 500,
            data: false
        })
        return
    }

    teacherData.splice(index, 1)

    res.send({
        msg: '删除成功',
        code: 200,
        data: true
    })
})

module.exports = router